// pages/detail/detail.js
import {
  timeSpan,
  isFullScreen
} from '../../utils/util.js';

import {
  Lock
} from '../../models/lock.js';

import {
  ContentModel
} from '../../models/content.js';

import {
  UserModel
} from '../../models/user.js';

import {
  enums
} from '../../utils/enums';

import {
  CommentModel
} from '../../models/comment.js';

import {
  Log
} from '../../utils/log.js';

import {
  Token
} from '../../utils/token.js';

const token = new Token();

const comment = new CommentModel();

const content = new ContentModel();

const user = new UserModel();

const lock = new Lock();

const log = new Log();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    contentId: "",
    content: {},
    isFullScreen: isFullScreen(),
    liked: false,
    collected: false,
    imgsLayout: true,
    loadingHidden: false,
    followed: false,
    comments: [],
    commentTotal: 0,
    // 计时开始
    timing: 0,
    // 定时器
    interval: "",
    logData: {
      // 页面入口来源：应用首页=1、详情页相关推荐=2
      "entry": 1,
      // 开始加载=1，加载成功=2（pv），加载失败=3, 退出页面=4
      "action": 1,
      // 内容ID（服务端下发的ID）
      "contentId": 0,
      // 图片数量
      "imgCount": 1,
      // 页面停留时长
      "stayTime": 0,
      // 加载时长
      "loadingTime": 0,
      // 加载失败码
      "errCode": "",
      // 分类ID
      "categoryId": 0
    },
    logPraiseFavoritesData: {
      "contentId": 0,
      // 分类ID
      "categoryId": 0
    },
    items: [],
    shareScene: false,
    likedNum: 0,
    collectedNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      contentId: options.id,
      logData: {
        "entry": options.entry,
        "contentId": options.id,
      },
      logPraiseFavoritesData: {
        "contentId": options.id,
      }
    })

    if (options.hasOwnProperty("type")) {
      // 分享场景
      this.setData({
        shareScene: true
      })

      this._mainLoad();
    } else {
      this._mainLoad();
    }

  },

  _mainLoad() {
    // 避免获取不到个人信息
    token.verify().then(res => {
      if (res) {
        this._loadData();
      }
    });
  },
  onHome() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  _loadData() {

    let that = this;
    let startTime = new Date().getTime();
    content.getOne(that.data.contentId).then(res => {

      // 内容详情
      let contentInfo = res.data;
      contentInfo.createTime = timeSpan(contentInfo.createTime);

      /**----------------------准备记录日志参数------------------------ */
      that.data.logData.loadingTime = new Date().getTime() - startTime;
      that.data.logData.action = 2;
      that.data.logData.imgCount = contentInfo.files.length;
      that.data.logData.tags = contentInfo.tags;

      that.setData({
        content: contentInfo,
        likedNum: contentInfo.likedNum,
        collectedNum: contentInfo.collectedNum,
        logData: that.data.logData
      })
      /**----------------------准备记录日志参数------------------------ */

      that._loadFollowed(contentInfo.userId);
      that._loadDetailRecommend(contentInfo);

      that._closeSkeletonView();

    }).catch(err => {
      /**----------------------准备记录日志参数------------------------ */
      that.data.logData.action = 3;
      that.data.logData.errCode = err.code;

      that.setData({
        logData: that.data.logData
      })
      that._reportAnalysis();
      /**----------------------准备记录日志参数------------------------ */
    });
  },

  /**
   * 用户是否收藏
   */
  _loadCollect() {
    user.ops(this.data.contentId, enums.collect, "history").then(res => {
      // 用户是否收藏
      this.setData({
        collected: res.data
      })
    });
  },

  /**
   * 用户是否点赞
   */
  _loadLiked() {
    user.ops(this.data.contentId, enums.like, "history").then(res => {
      this.setData({
        liked: res.data,
      })
    });
  },

  /**
   * 获取评论简介
   */
  _loadComments() {
    comment.getCommentsByContentId(this.data.contentId, 1, 2).then(res => {
      res.data.result.forEach(e => {
        e.createTime = timeSpan(e.createTime);
      })
      this.setData({
        comments: res.data.result,
        commentTotal: res.data.total
      })
    });
  },

  /**
   * 是否关注
   */
  _loadFollowed(userId) {
    let that = this;
    user.followed(userId).then(res => {
      that.setData({
        followed: res.data
      })
    })
  },

  /**
   * 详情推荐
   */
  _loadDetailRecommend(contentInfo) {
    let that = this;
    let tags = contentInfo.tags.length > 0 ? contentInfo.tags : [];
    content.detailRecommend(contentInfo.content, contentInfo.id, contentInfo.userId, tags).then(res => {
      that.setData({
        items: res.data,
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._loadCollect();
    this._loadLiked();
    this._loadComments();
    // 计算页面停留时长
    this._countTime();

    // let switchViewTip = wx.getStorageSync(enums.switchViewTip);
    // if (!switchViewTip) {
    //   // 开启提示
    //   this.setData({
    //     switchViewTip: !switchViewTip
    //   })

    //   // 3秒之后关闭提示
    //   setTimeout(() => {
    //     wx.setStorageSync(enums.switchViewTip, !switchViewTip);
    //     this.setData({
    //       switchViewTip: switchViewTip
    //     })
    //   }, 3000);
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 跳转其他页面时,停止计时
    this._pauseTiming();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    that.data.logData.stayTime = this.data.timing;
    that.setData({
      logData: that.data.logData
    })
    // 上报日志
    that._reportAnalysis();
    // 移除计时器
    that._pauseTiming();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.content.content,
      path: `/pages/detail/detail?id=${this.data.contentId}&type=share`,
      imageUrl: this.data.content.coveredImg.url,
    }
  },
  onLike(e) {

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    let id = e.currentTarget.dataset.id;
    let userId = e.currentTarget.dataset.userId;
    user.ops(id, enums.like, 'ops', userId)
      .then(res => {
        setTimeout(() => {
          this.setData({
            liked: res.data.result,
            likedNum: res.data.likedNum
          });

          if (res.data) {
            this._reportPraiseAnalysis();
          }

        }, 300);

        lock.unlock();
      }).catch(err => {
        lock.unlock();
      });
  },
  onCollect(e) {

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    let id = e.currentTarget.dataset.id;
    user.ops(id, enums.collect)
      .then(res => {
        setTimeout(() => {
          this.setData({
            collected: res.data.result,
            collectedNum: res.data.collectedNum
          });

          if (res.data) {
            this._reportFavoritesAnalysis();
          }

        }, 300);

        lock.unlock();
      }).catch(err => {
        lock.unlock();
      });
  },
  onRightTap() {
    if (this.data.content.files.length > 1) {
      this.setData({
        imgsLayout: !this.data.imgsLayout
      })
    }
  },
  onComment(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../comment/comment?contentId=${id}`,
    })
  },
  _closeSkeletonView() {
    this.setData({
      loadingHidden: false
    });
  },
  onAccount(e) {
    let userId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../profile/profile?userId=${userId}`,
    })
  },
  onFollow(e) {

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    let userId = e.currentTarget.dataset.userId;
    user.follow(userId, this.data.followed).then(res => {

      // followed -> true:已关注,false:关注
      let result = this.data.followed ? !res.data : res.data;
      setTimeout(() => {
        this.setData({
          followed: result
        });

      }, 600);

      // 关注成功,上报日志
      if (result) {
        log.logFollow(userId);
      }

      lock.unlock();
    }).catch(err => {
      console.log(err);
      lock.unlock();
    });
  },
  _reportAnalysis() {
    log.logDetail(this.data.logData);
  },
  _reportPraiseAnalysis() {
    log.logPraise(this.data.logPraiseFavoritesData);
  },
  _reportFavoritesAnalysis() {
    log.logFavorites(this.data.logPraiseFavoritesData);
  },
  _countTime() {
    let that = this;
    let times = that.data.timing;

    let timer = setInterval(function () {
      that.setData({
        timing: times++
      })
    }, 1000);

    this.setData({
      interval: timer
    })
  },
  _pauseTiming() {
    clearInterval(this.data.interval)
  },
  onTag(e) {
    let q = e.currentTarget.dataset.text;
    wx.navigateTo({
      url: `../search/search?q=${q}`,
    })
  },
  toDetail(e) {
    let params = e.detail;

    // 记录日志
    log.logHistory(params.id);

    // 跳转到详情页
    wx.navigateTo({
      url: `../detail/detail?id=${params.id}&entry=2`,
    });
  }
})